/* eslint-disable no-prototype-builtins */
import React, { useState } from 'react';
import s from './style.module.css';
import {
  Input,
  Radio,
  Datetime,
  Checkbox,
  Form,
  Message,
  Helper,
  Dialog,
  Button,
  Confirm,
  Switch,
  Textarea,
  Select
} from '@knownsec/react-component';
import {  Link } from 'react-router-dom';
import cn from 'classnames';

import TimePicker from '../../../test/TimePicker';
import moment from 'moment';
// import SelectAnt from '@/test/SelectAnt';
import CollectFrequency from '@/components/CollectFrequency';
import recursionForm from '@/common/recursionForm';
import { getWarnUserList,getTaskList } from '~/API';
import addIcon from "@/assets/svg/basicAdd.svg"
import delIcon from "@/assets/svg/basicDel.svg"
import i from '@/index.module.css';
import Icon from '@/assets/icon'
const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 },
};
import { deepClone } from '@/common/constant.js';
export default function Basic({ formData, params, sysinfo={},onChange }) {
  let defaultData = {
    target_group_name: '',
    target_url: '',
    target_urls: [],
    ...formData.task_config,
  };
  const [isOnce, setIsOnce] = useState(false);
  const [promptly, setPromptly] = useState(false);
  const [showInp, setShowInp] = useState(false);
  const [visible, setVisible] = useState(false);
  const [targetList, setTargetList] = useState([]);
  const [singeTaskDisable, setDisable] = useState(false);
  const [disAlert, setDisAlert] = useState({
    availability: true,
    securityEvent: true,
    vul: true,
    risk_link: true,
    change_check: true,
  });
  const [userLIst, setUserLIst] = useState([]);
  //获取告警人列表
  const alertUser = async () => {
    const user = await getWarnUserList({ all: 1 }).catch(err =>{return false;});
    if(user){
      const user_ = user.data.data.map((e) => {
        return { label: e.contact_name, value: e.receiver_id };
      });
      setUserLIst(user_);
      initData(user_);
    }
  
  };
  const getSingle=async()=>{
    setVisible(true)
    const res= await getTaskList(params.data.id)
    setTargetList(res.data.data)
  }
  //初始化Formdata
  const initData = (user_) => {
    const task_config = formData.task_config||{};
    setDisable(!task_config?.is_solo);
    const day_at_start = task_config?.scan_period_start_time ? moment(task_config.scan_period_start_time, 'HH:mm:ss'): ''
    const day_at_end = task_config?.scan_period_end_time ? moment(task_config.scan_period_end_time, 'HH:mm:ss') : ''
    const scan_period = [
      task_config?.start_at ? moment(task_config.start_at) : '',
      task_config?.end_at ? moment(task_config.end_at) : '',
    ];
    const target_urls = formData.target_urls.join('\n');
    const objTask = {};
    const disAlert_ = {};
    ['vul', 'securityEvent', 'availability', 'risk_link','change_check'].forEach((e) => {
        const val=sysinfo.includes(e)?task_config[e]?.is_disabled:true;
      objTask[e] = {
        is_disabled: !val,
        seconds: task_config[e]?.seconds,
      };
      disAlert_[e] = val;
    //   task_config.warn_info[e]=!val
    });
    const receiver_list=task_config?.receiver_list[0] ? task_config.receiver_list : [user_[0].value]
    createForm.current.setFieldsValue({
      ...objTask,
      is_solo: Boolean(task_config.is_solo),
      target_urls,
      target_group_name: formData.target_group_name,
      scan_period,
      day_at_start,
      day_at_end,
      start_at: moment(task_config.start_at),
      is_periodic: task_config.is_periodic,
      use_increment: task_config.use_increment,
      promptly: task_config.promptly,
      warn_info: task_config.warn_info,
      receiver_list,
    });
    setPromptly(task_config.promptly);
    setIsOnce(!task_config.is_periodic);
    setDisAlert(disAlert_);
  };
  const createForm = React.useRef();

  function disabledDate(current) {
    return current && current < moment(new Date(
        moment().subtract(0, "days").format("YYYY-MM-DD 00:00:00")
      ));
  }
  //任务组组件
  const retForm = () => {
    return (
      <>
        <div className={s.BasicInpBox}>
          {params.type === 'solo' && (
            <Form.Item
              name="is_solo"
              valuePropName="checked"
              label={
                <span>
                启用单个业务系统设置
                  <Helper
                    className="paddingHelp"
                    placement="top"
                    overlay="开启后，监测此站点时将忽略任务组相关配置。"
                  ></Helper>
                </span>
              }
              className={s.itemSolo}
            >
              <Switch pro />
            </Form.Item>
          )}
          <Form.Item
            name="target_urls"
            label="监测业务系统:"
            rules={[{ required: true, message: '请输入监测业务系统' }]}
          >
            <Textarea
              className={cn(s.textArea, s.bors)}
              disabled={params.type === 'solo'||params.type === 'group'}
              placeholder="支持IPV6、IPV4格式，可提交多个业务系统，按换行分割。&#13;&#10;http://www.example&#13;&#10;http://[AD80:0000:0000:0000:ABAA:0000:00C2:0002]&#13;&#10;https://1.1.1.1"
            ></Textarea>
          </Form.Item>
          { params.type === 'group'&&<img className={s.eidte} src={addIcon} alt="" onClick={()=>{
            setShowInp(true)}}/>}
          { params.type === 'group'&&<span className={s.eidte2} onClick={()=>{getSingle()}}>查看启用单个配置的业务系统</span>}
        </div>
        {showInp&& <div className={s.BasicInpBox}>
          <Form.Item
            name="target_urls2"
          >
            <Textarea
              className={cn(s.textArea2, s.bors)}
              placeholder="支持IPV6、IPV4格式，可提交多个业务系统，按换行分割。&#13;&#10;http://www.example&#13;&#10;http://[AD80:0000:0000:0000:ABAA:0000:00C2:0002]&#13;&#10;https://1.1.1.1"
            ></Textarea>
          </Form.Item>
          <img className={s.eidte} src={delIcon} alt="" onClick={()=>{
            setShowInp(false)}}/>
        </div>}
        <Form.Item
          name="target_group_name"
          label="任务组名称"
          valuePropName="value"
          rules={[{ required: true, message: '请输入任务组名称' }]}
        >
          <Input
            pro
            className={s.w_25}
            disabled={params.type === 'solo'}
            placeholder="请输入中文、英文或数字，不超过32个字符"
            type="text"
            autoComplete={'off'}
            maxlength={32}
          />
        </Form.Item>
        <Form.Item name="is_periodic" label="任务类型">
          <Radio.Group className={s.radioBorder}>
            <Radio value={true} className={s.radio0} disabled={params.type === 'group'||params.type === 'solo'}>
              周期任务
            </Radio>
            <Radio value={false} className={s.radio0} disabled={params.type === 'group'||params.type === 'solo'}>
              单次任务
            </Radio>
          </Radio.Group>
        </Form.Item>
        <div className={s.HelperBox}>
          <Form.Item name="use_increment" 
          valuePropName="checked"
          label={
            <span>增量扫描<Helper
            className="paddingHelp"
            placement="top"
            overlay="启用增量扫描，系统将对比上次扫描信息，仅对新增资产进行安全监测，默认15天周期重置。"
            ></Helper></span>} 
          className={s.title}>
            <Switch pro className={s.Switch} disabled={singeTaskDisable && params.type === 'solo'}></Switch>
          </Form.Item>
         
        </div>
        {isOnce ? (
          <>
            <Form.Item name="promptly" label="执行时间" className={s.itemExtra}>
              <Radio.Group className={s.radioBorder}>
                <Radio value={true} className={s.radio0} disabled={singeTaskDisable && params.type === 'solo'}>
                  立即
                </Radio>
                <Radio value={false} className={s.radio0} disabled={singeTaskDisable && params.type === 'solo'}>
                  指定时间
                </Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              name="start_at"
              className={s.onceTime}
              style={{ display: !promptly ? 'block' : 'none' }}
            >
              <Datetime disabledDate={disabledDate} className={s.datetimes}  disabled={singeTaskDisable && params.type === 'solo'}/>
            </Form.Item>
          </>
        ) : (
          <>
            <Form.Item name="scan_period" label="周期监测时间段">
              <Datetime useDefault showTime disabled={singeTaskDisable && params.type === 'solo'} disabledDate={disabledDate} className={s.datetimes} />
            </Form.Item>
            <Form.Item label="每天监测时间段" validateStatus={timeTip?.type} help={timeTip?.message} >
              <Form.Item name="day_at_start" style={{display: 'inline-block', marginRight: '5px', marginBottom: '2px' }}>
                <TimePicker className={s.locale} disabled={singeTaskDisable && params.type === 'solo'} format="HH:mm" placeholder='开始时间'/>
              </Form.Item>
              <Form.Item name="day_at_end" style={{display: 'inline-block', marginBottom: '2px' }}>
                <TimePicker className={s.locale} disabled={singeTaskDisable && params.type === 'solo'} format="HH:mm" placeholder='结束时间'/>
              </Form.Item>
            </Form.Item>
          </>
        )}
        <Form.Item label="监测项">
          <div className={s.monitorItem} style={{ width: isOnce ? '13.5rem' : '31rem' }}>
            <Form.Item
              name={['availability', 'is_disabled']}
              className={s.mTtem}
              valuePropName="checked"
            >
              <Checkbox disabled={(singeTaskDisable && params.type === 'solo')||!sysinfo.includes('availability')}>可用性</Checkbox>
            </Form.Item>
            <div style={{ display: isOnce ? 'none' : 'block' }}>
              <Form.Item name={['availability', 'seconds']}>
                <CollectFrequency disabled={(singeTaskDisable && params.type === 'solo')||!sysinfo.includes('availability')}></CollectFrequency>
              </Form.Item>
            </div>

            <Form.Item
              name={['securityEvent', 'is_disabled']}
              className={s.mTtem}
              valuePropName="checked"
            >
              <Checkbox disabled={(singeTaskDisable && params.type === 'solo')||!sysinfo.includes('securityEvent')}>安全事件</Checkbox>
            </Form.Item>
            <div style={{ display: isOnce ? 'none' : 'block' }}>
              <Form.Item name={['securityEvent', 'seconds']}>
                <CollectFrequency disabled={(singeTaskDisable && params.type === 'solo')||!sysinfo.includes('securityEvent')}></CollectFrequency>
              </Form.Item>
            </div>
          </div>
          <div className={s.monitorItem} style={{ width: isOnce ? '13.5rem' : '31rem' }}>
            <Form.Item name={['vul', 'is_disabled']} className={s.mTtem} valuePropName="checked">
              <Checkbox disabled={(singeTaskDisable && params.type === 'solo')||!sysinfo.includes('vul')}>漏洞</Checkbox>
            </Form.Item>
            <div style={{ display: isOnce ? 'none' : 'block' }}>
              <Form.Item name={['vul', 'seconds']}>
                <CollectFrequency disabled={(singeTaskDisable && params.type === 'solo')||!sysinfo.includes('vul')}></CollectFrequency>
              </Form.Item>
            </div>
            <Form.Item
              name={['risk_link', 'is_disabled']}
              className={s.mTtem}
              valuePropName="checked"
            >
              <Checkbox disabled={(singeTaskDisable && params.type === 'solo')||!sysinfo.includes('risk_link')}>风险外链</Checkbox>
            </Form.Item>
            <div style={{ display: isOnce ? 'none' : 'block' }}>
              <Form.Item name={['risk_link', 'seconds']}>
                <CollectFrequency disabled={(singeTaskDisable && params.type === 'solo')||!sysinfo.includes('risk_link')}></CollectFrequency>
              </Form.Item>
            </div>
          </div>
          <div className={s.monitorItem} style={{ width:'15.25rem', display: isOnce ? 'none' : 'flex'  }}>
          <Form.Item
              name={['change_check', 'is_disabled']}
              className={s.mTtem}
              valuePropName="checked"
            >
              <Checkbox disabled={(singeTaskDisable && params.type === 'solo')||!sysinfo.includes('change_check')}>篡改</Checkbox>
            </Form.Item>
            <div  style={{ display: 'block' }}>
              <Form.Item name={['change_check', 'seconds']}>
                <CollectFrequency disabled={(singeTaskDisable && params.type === 'solo')||!sysinfo.includes('change_check')}></CollectFrequency>
              </Form.Item>
            </div>
          </div>
        </Form.Item>
        <Form.Item name={'receiver_list'} label="告警联系人">
          <Select
            multiple
            pro
            option={userLIst}
            disabled={singeTaskDisable && params.type === 'solo'}
            className={s.w_25}
            placeholder="请选择告警人"
          />
        </Form.Item>
        <Form.Item label="告警监测项" className={s.alertType}>
          <Form.Item
            name={['warn_info', 'availability']}
            className={s.mTtem}
            valuePropName="checked"
          >
            <Checkbox disabled={disAlert.availability||(singeTaskDisable && params.type === 'solo')}>可用性</Checkbox>
          </Form.Item>
          <Form.Item
            name={['warn_info', 'securityEvent']}
            className={s.mTtem}
            valuePropName="checked"
          >
            <Checkbox disabled={disAlert.securityEvent||(singeTaskDisable && params.type === 'solo')}>安全事件</Checkbox>
          </Form.Item>
          <Form.Item name={['warn_info', 'vul']} className={s.mTtem} valuePropName="checked">
            <Checkbox disabled={disAlert.vul||(singeTaskDisable && params.type === 'solo')}>漏洞</Checkbox>
          </Form.Item>
          <Form.Item name={['warn_info', 'risk_link']} className={s.mTtem} valuePropName="checked">
            <Checkbox disabled={disAlert.risk_link||(singeTaskDisable && params.type === 'solo')}>风险外链</Checkbox>
          </Form.Item>
          <Form.Item name={['warn_info', 'change_check']} className={s.mTtem} valuePropName="checked" style={{ display: isOnce ? 'none' : 'block' }}>
            <Checkbox disabled={disAlert.change_check||(singeTaskDisable && params.type === 'solo')}>篡改</Checkbox>
          </Form.Item>
        </Form.Item>
      </>
    );
  };
  const [timeTip, setTimeTip] = useState(null)
  //表单值绑定
  const onValues = (data, allValues) => {
    const arrTask = ['vul', 'securityEvent', 'availability', 'risk_link','change_check'];
    const values = recursionForm(data)
    const valuesKey = Object.keys(values)[0];
    setTimeTip(null)
    createForm.current.setFieldsValue(values);
    if(values.hasOwnProperty('is_solo')){
      setDisable(!values.is_solo);
      onChange('task_config', { is_solo: Boolean(values.is_solo) });
    }else if (values.hasOwnProperty('scan_period')) {
      let start_at = '';
      let end_at = '';
      if (values['scan_period']) {
        start_at = moment(values.scan_period[0]._d);
        end_at = values.scan_period[1] ? moment(values.scan_period[1]._d) : '';
      } else {
        createForm.current.setFieldsValue({
          scan_period: [],
        });
      }
      onChange('task_config', { start_at, end_at });
      return;
    } else if (values.hasOwnProperty('day_at_start') || values.hasOwnProperty('day_at_end')) {
      let scan_period_start_time = '';
      let scan_period_end_time = '';
      if (values['day_at_start']) {
        scan_period_start_time = moment(values.day_at_start._d).seconds(0).format('HH:mm:ss');
        scan_period_end_time = moment(createForm.current.getFieldsValue().day_at_end._d).seconds(0).format('HH:mm:ss');
      }
      if (values['day_at_end']) {
        scan_period_start_time = moment(createForm.current.getFieldsValue().day_at_start._d).seconds(0).format('HH:mm:ss');
        scan_period_end_time = moment(values.day_at_end._d).seconds(0).format('HH:mm:ss');
      }
      let diffM = moment(scan_period_end_time, 'HH:mm:ss').diff(moment(scan_period_start_time, 'HH:mm:ss'), 'minutes')
      diffM = diffM < 0 ? diffM + (24 * 60) : diffM
      if (diffM > (18 * 60)) {
        setTimeTip({ type: 'error', message: '时间段最大范围为18小时，请重新选择' })
      } else if (diffM < (6 * 60)) {
        setTimeTip({ type: 'error', message: '时间段最小范围为6小时，请重新选择' })
      }
      onChange('task_config', { scan_period_start_time, scan_period_end_time });
      return;
    } else if (values.hasOwnProperty('target_urls')) {
      values.target_urls = values.target_urls.trim().split('\n');
      onChange('', values);
      return;
    }else if (values.hasOwnProperty('target_urls2')) {
      //任务组修改合并到原字段里
      const target_urls2 = values.target_urls2.trim().split('\n');
      let target_urls = allValues.target_urls.trim().split('\n');
      target_urls=[...new Set(target_urls.concat(target_urls2))].filter((e)=>{return e})
      onChange('', {target_urls});
      return;
    }  else if (values.hasOwnProperty('target_group_name')) {
      onChange('', values);
      return;
    } else if (values.hasOwnProperty('warn_info')) {
      const obj = { warn_info: { ...allValues.warn_info, ...values.warn_info } };
      onChange('task_config', obj);
      return;
    } else if (values.hasOwnProperty('receiver_list')) {
      onChange('task_config', values);
      return;
    } else if (arrTask.includes(valuesKey)) {
      const values_=deepClone(values)
      const v1 = typeof values[valuesKey]?.is_disabled === 'object' ? values[valuesKey]?.is_disabled?.value : values[valuesKey]?.is_disabled
      const v2 = typeof allValues[valuesKey]?.is_disabled === 'object' ? allValues[valuesKey]?.is_disabled?.value : allValues[valuesKey]?.is_disabled
      if (v1 || v1 == false) {
        const is_disabled = v1
        values_[valuesKey].is_disabled = !is_disabled;
        const obj = {
          [valuesKey] : {
            is_disabled: v1
          }
        }
        //告警根据监测项改变
        const warn_info = { ...allValues.warn_info, [valuesKey]: is_disabled };
        createForm.current.setFieldsValue({ warn_info: { [valuesKey]: is_disabled }, ...obj });
        onChange('task_config', { warn_info });
      } else {
        values[valuesKey].is_disabled = !v2;
      }
      if(v1!==undefined) {
        setDisAlert({ ...disAlert, [valuesKey]: !v1 });
      }
      values_[valuesKey].seconds = allValues[valuesKey].seconds;
      onChange('task_config', values_);
    }
    if (values.hasOwnProperty('is_periodic')) {
      setIsOnce(!values.is_periodic);
      if (values.is_periodic) {
        values.start_at = '';
        values.end_at = '';
        createForm.current.setFieldsValue({
          day_at_start: '',
          day_at_end: ''
        });
        onChange('task_config', { scan_period_start_time: '', scan_period_end_time: '' });
      } else {
        values.start_at = moment();
        values.end_at = moment().add(1, 'H');
        createForm.current.setFieldsValue({ start_at: moment() });
      }
    }
    if (values.hasOwnProperty('promptly')) {
      setPromptly(values.promptly);
      values.start_at = moment();
      createForm.current.setFieldsValue({ start_at: moment() });
    }
    onChange('task_config', values);
  };
  React.useMemo(() => {}, []);
  React.useEffect(() => {
    alertUser();
  }, [formData]);
  return (
    <div className={s.main}>
      <Form
        {...layout}
        ref={createForm}
        initialValues={defaultData}
        name="control-ref"
        onValuesChange={(newItem, allValues) => {
          if("is_solo" in newItem) {
            const value=newItem.is_solo
            let msg=value?'启用后，此业务系统检测配置将单独控制，不受任务组配置影响，您确定要启用吗？':'关闭后，此业务系统检测将按对应任务组配置检测，您确定要关闭吗？'
            Confirm({
              pro: true,
              title: '提示',
              className: s.dialogName,
              message: <div className="confirmbox">{msg}</div>,
              onconfirm:  () => {onValues(newItem, allValues);},
              oncancel: () => {
                createForm.current.setFieldsValue({is_solo:!value});
              },
            });
          }else{
            onValues(newItem, allValues);
          }
        }}
      >
        {retForm()}
      </Form>
      <Dialog
        className={s.w400}
        title="启用单个配置业务系统列表"
        cancelText=""
        confirmText=""
        onhide={() => setVisible(false)}
        visible={visible}
      >
        <div className={s.total}>共计{targetList.length}条</div>
        <div className={s.soloBox}>
          <table>
            <thead>
              <tr>
                <td style={{'padding-left':'0.5rem'}}>业务系统</td>
                <td>基本信息</td>
                <td>监测配置</td>
                <td>高级扫描配置</td>
              </tr>
            </thead>
            <tbody>
              {targetList.map((e)=>{
                return (<tr key={e}>
                  <td>
                    <Link
                      to={{
                        pathname: '/form_page',
                        search: `id=${e.target_id}&type=solo`,
                      }}
                      className={s.hostTd}
                      target="_blank" 
                      onClick={() => { setVisible(false)}}
                    > {e.target_url}</Link>
                    <p className={s.hostTd}>{e.target_name||'--'}</p>
                  </td>
                  <td>{e.task_config?.is_solo?Icon({active:'gou'}):'--'}</td>
                  <td>{e.job_config_map?.is_solo?Icon({active:'gou'}):'--'}</td>
                  <td>{e.advance_config?.is_solo?Icon({active:'gou'}):'--'}</td>
                </tr>)
              })}
            </tbody>
          </table>
        </div>
        <div className={cn(i.tac, s.dioBtn)}>
          <Button type="primary" className={cn(i.ml24, i.vam)} onClick={() => { setVisible(false)}}>
            确定
          </Button>
        </div>
      </Dialog>
    </div>
  );
}
